import storage from 'good-storage'

const ORDER_KEY = '__book_order__'


export function loadOrder() {
    return storage.get(ORDER_KEY, [])
}

export function saveOrder(query) {
    let orders= storage.get(ORDER_KEY,[]);

    orders.forEach((item,index)=>{
        if(item.book_id===query.book_id) {
            item.order_num++;
            return;
        }
    })
    let ind = orders.findIndex((item)=>{
        return item.book_id===query.book_id
    })
    if(ind<0) {
        orders.push(Object.assign({order_num:1},query))
    }
    storage.set(ORDER_KEY,orders)
    return orders;

}

export function deleteOrder(query) {
    let orders = storage.get(ORDER_KEY, []);
    orders.forEach((item, index) => {
        if (item.book_id === query.book_id) {
            if(item.order_num>1) {
                item.order_num--;
            }else{
                orders.splice(index,1)
            }
            return;
        }
    })
    storage.set(ORDER_KEY,orders)
    return orders;
}
